<template>
  <div>
    <!-- 搜索区域 -->
    <el-card>
      <el-form ref="searchFormRef" :model="searchData" :inline="true">
        <el-form-item label="标签名称" prop="tag_name">
          <el-input v-model="searchData.tag_name" placeholder="标签名称" clearable />
        </el-form-item>

        <el-form-item label="是否显示" prop="is_show">
          <el-select v-model="searchData.is_show" placeholder="全部" clearable style="width: 100px">
            <el-option label="全部" value="" />
            <el-option label="显示" :value="1" />
            <el-option label="不显示" :value="0" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="search" @click="search">搜索</el-button>
          <el-button icon="refresh" @click="reset(searchFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card>
      <!-- 标签表格 -->
      <el-table ref="tagTableRef" :data="tagData" style="width: 100%">
        <!-- 多选框 -->
        <el-table-column type="selection" width="55" />

        <el-table-column label="序号">
          <template #default="{ $index }">
            {{ $index + 1 }}
          </template>
        </el-table-column>
        <el-table-column label="标签名">
          <template #default="{ row }">
            {{ row.tag_name }}
          </template>
        </el-table-column>
        <el-table-column label="是否显示">
          <template #default="{ row }">
            {{ row.is_show ? "显示" : "隐藏" }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="30">
          <template #default="{ row }">
            <el-button link type="primary" @click="edit(row)">编辑</el-button>
            <el-button link type="primary" @click="del(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 按钮和分页 -->
      <div class="button">
        <el-button @click="delSel">删除选中标签</el-button>
        <el-button @click="openTagForm">添加标签</el-button>
        <el-pagination
          background
          :total="tagCount"
          :page-size="pagesize"
          :current-page="page"
          layout="prev, pager, next, total"
          @current-change="changePage"
        />
      </div>
    </el-card>

    <!-- 标签的表单 -->
    <div class="tagForm" v-if="isShow">
      <el-form :model="newTagData" ref="ruleFormRef" :rules="rules">
        <el-form-item label="标签名称" prop="tag_name">
          <el-input v-model="newTagData.tag_name" />
        </el-form-item>
        <el-form-item label="是否显示" prop="is_show">
          <el-switch v-model="newTagData.is_show" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="confirm(ruleFormRef)">
            {{ addOrEdit === "add" ? "添加" : "修改" }}
          </el-button>
          <el-button @click="cancel(ruleFormRef)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import TagAPI, { type TagData, NewTagData, SearchData } from "@/api/system/tag.api";
import type { FormInstance, FormRules } from "element-plus";
import { useTemplateRef } from "vue";

const tagData = ref<TagData[]>(); // 标签数据
const page = ref(1); // 页码
const pagesize = ref(2); // 每页显示的个数
const tagCount = ref(0); // 数据的总数量
const isShow = ref(false); // 标签表单的显隐
const addOrEdit = ref(""); // 表单的数据
const newTagData = ref<NewTagData>({
  tag_id: 0,
  tag_name: "",
  is_show: false,
});
const ruleFormRef = ref<FormInstance>(); // 表单校验
// 自定义校验,校验标签名是否重复
const validateName = (rules: any, value: any, callback: any) => {
  TagAPI.verifyTagName(newTagData.value.tag_id, value).then(() => {
    callback();
  });
};
const rules = ref<FormRules<NewTagData>>({
  // 表单输入规则
  tag_name: [
    { required: true, message: "请输入标签名称", trigger: "blur" },
    { validator: validateName, trigger: "blur" },
  ],
});

const tagTableRefCom = useTemplateRef("tagTableRef"); // 绑定组件实例
const searchData = ref<SearchData>({
  tag_name: "",
  is_show: "",
});

onMounted(() => {
  getTagData();
});
const searchFormRef = ref<FormInstance>();

// 重置
const reset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  getTagData();
};

// 搜索
const search = () => {
  getTagData();
};

// 编辑
const edit = async (row: TagData) => {
  addOrEdit.value = "edit";
  isShow.value = true;
  let editedTagData = await TagAPI.editedTagData(row.tag_id);
  console.log(editedTagData);
  editedTagData.is_show = editedTagData.is_show ? true : false;
  newTagData.value = editedTagData;
};

// 删除选中标签
const delSel = async () => {
  let selDelRow = tagTableRefCom.value!.getSelectionRows();
  let tag_ids = selDelRow.map((item: TagData) => item.tag_id);
  if (tag_ids.length === 0) {
    ElMessage.info("请选择标签");
    return;
  }
  await TagAPI.delSelTagData(tag_ids);
  getTagData();
  ElMessage.success("删除选中标签成功");
};

// 删除
const del = (row: TagData) => {
  ElMessageBox.confirm(`确定删除 ${row.tag_name} 吗?`, "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await TagAPI.delTagData(row.tag_id);
      getTagData();
      ElMessage({
        type: "success",
        message: "删除标签成功",
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

// 确定
const confirm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (valid) {
      newTagData.value.is_show = newTagData.value.is_show ? 1 : 0;
      if (addOrEdit.value === "add") {
        await TagAPI.addTagData(newTagData.value);
      } else {
        await TagAPI.editTagData(newTagData.value);
      }
      isShow.value = false;
      formEl.resetFields(); // 重置表单
      getTagData();
      ElMessage.success((addOrEdit.value === "add" ? "添加" : "修改") + "标签成功");
    }
  });
};

// 取消
const cancel = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  isShow.value = false;
  formEl.resetFields(); // 重置表单
};

// 添加标签数据
const openTagForm = async () => {
  addOrEdit.value = "add";
  isShow.value = true;
};

// 获取标签数据和数量
const getTagData = async () => {
  let data = await TagAPI.getTag(
    page.value,
    pagesize.value,
    searchData.value.tag_name,
    searchData.value.is_show
  );
  tagData.value = data.tagData;
  tagCount.value = data.tagCount;
};

// 改变页码
const changePage = (newPage: number) => {
  page.value = newPage;
  getTagData();
};
</script>

<style scoped>
.button {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-top: 20px;
}

.tagForm {
  position: fixed;
  top: 0;
  left: 0;
  /* 半透明遮罩 */
  z-index: 2000;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  /* 确保在最上层 */
}

.tagForm .el-form {
  width: 600px;
  padding: 30px 30px 20px 30px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>
